#include "CocosWidget.h"
#include <QMouseEvent>
#include <QSurfaceFormat>
#include <QPainter>
#include <QDebug>
#include <cmath>

CocosWidget::CocosWidget(QWidget* parent)
    : QOpenGLWidget(parent)
    , m_shaderProgram(nullptr)
    , m_vertexBuffer(nullptr)
    , m_vao(nullptr)
    , m_lastFrameTime(0.0f)
    , m_initialized(false)
    , m_frameCount(0)
    , m_fpsUpdateTimer(0.0f)
    , m_currentFPS(0.0f)
    , m_rotation(0.0f)
{
    // 设置焦点策略，确保能接收键盘事件
    setFocusPolicy(Qt::StrongFocus);

    // 启用鼠标追踪（即使不按下也能收到移动事件）
    setMouseTracking(true);

    // 配置OpenGL格式
    QSurfaceFormat format;
    format.setVersion(3, 3);              // OpenGL 3.3 Core
    format.setProfile(QSurfaceFormat::CoreProfile);
    format.setDepthBufferSize(24);        // 深度缓冲
    format.setStencilBufferSize(8);       // 模板缓冲
    format.setSamples(4);                 // MSAA 4x抗锯齿
    format.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
    setFormat(format);

    qDebug() << "[CocosWidget] Initialized with OpenGL format:" << format;
}

CocosWidget::~CocosWidget() {
    qDebug() << "[CocosWidget] Destructor called";
    cleanup();
}

void CocosWidget::initializeGL() {
    qDebug() << "[CocosWidget] initializeGL() called";

    // 初始化OpenGL函数
    initializeOpenGLFunctions();

    // 打印OpenGL信息
    qDebug() << "[CocosWidget] OpenGL Vendor:" << (const char*)glGetString(GL_VENDOR);
    qDebug() << "[CocosWidget] OpenGL Renderer:" << (const char*)glGetString(GL_RENDERER);
    qDebug() << "[CocosWidget] OpenGL Version:" << (const char*)glGetString(GL_VERSION);
    qDebug() << "[CocosWidget] GLSL Version:" << (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION);

    // 设置清屏颜色（深色背景）
    glClearColor(0.1f, 0.1f, 0.15f, 1.0f);

    // 启用深度测试
    glEnable(GL_DEPTH_TEST);

    // 初始化着色器和几何数据
    initializeShaders();
    initializeTriangle();

    m_initialized = true;
    m_timer.start();
    m_lastFrameTime = m_timer.elapsed() / 1000.0f;

    qDebug() << "[CocosWidget] Initialization completed";
}

void CocosWidget::initializeShaders() {
    qDebug() << "[CocosWidget] Initializing shaders...";

    // 创建着色器程序
    m_shaderProgram = new QOpenGLShaderProgram(this);

    // 顶点着色器
    const char* vertexShaderSource = R"(
        #version 330 core
        layout (location = 0) in vec3 aPos;
        layout (location = 1) in vec3 aColor;

        out vec3 vertexColor;

        uniform mat4 transform;

        void main() {
            gl_Position = transform * vec4(aPos, 1.0);
            vertexColor = aColor;
        }
    )";

    // 片段着色器
    const char* fragmentShaderSource = R"(
        #version 330 core
        in vec3 vertexColor;
        out vec4 FragColor;

        void main() {
            FragColor = vec4(vertexColor, 1.0);
        }
    )";

    // 编译着色器
    if (!m_shaderProgram->addShaderFromSourceCode(QOpenGLShader::Vertex, vertexShaderSource)) {
        qCritical() << "[CocosWidget] Vertex shader compilation failed:" << m_shaderProgram->log();
        return;
    }

    if (!m_shaderProgram->addShaderFromSourceCode(QOpenGLShader::Fragment, fragmentShaderSource)) {
        qCritical() << "[CocosWidget] Fragment shader compilation failed:" << m_shaderProgram->log();
        return;
    }

    // 链接着色器程序
    if (!m_shaderProgram->link()) {
        qCritical() << "[CocosWidget] Shader program linking failed:" << m_shaderProgram->log();
        return;
    }

    qDebug() << "[CocosWidget] Shaders initialized successfully";
}

void CocosWidget::initializeTriangle() {
    qDebug() << "[CocosWidget] Initializing triangle...";

    // 三角形顶点数据（位置 + 颜色）
    // 每个顶点：x, y, z, r, g, b
    float vertices[] = {
        // 位置            // 颜色
         0.0f,  0.5f, 0.0f,  1.0f, 0.0f, 0.0f,  // 顶部 - 红色
        -0.5f, -0.5f, 0.0f,  0.0f, 1.0f, 0.0f,  // 左下 - 绿色
         0.5f, -0.5f, 0.0f,  0.0f, 0.0f, 1.0f   // 右下 - 蓝色
    };

    // 创建VAO
    m_vao = new QOpenGLVertexArrayObject(this);
    m_vao->create();
    m_vao->bind();

    // 创建VBO
    m_vertexBuffer = new QOpenGLBuffer(QOpenGLBuffer::VertexBuffer);
    m_vertexBuffer->create();
    m_vertexBuffer->bind();
    m_vertexBuffer->allocate(vertices, sizeof(vertices));

    // 配置顶点属性
    // 位置属性
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);

    // 颜色属性
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float)));
    glEnableVertexAttribArray(1);

    // 解绑
    m_vao->release();
    m_vertexBuffer->release();

    qDebug() << "[CocosWidget] Triangle initialized successfully";
}

void CocosWidget::resizeGL(int w, int h) {
    qDebug() << "[CocosWidget] resizeGL:" << w << "x" << h;
    glViewport(0, 0, w, h);
}

void CocosWidget::paintGL() {
    if (!m_initialized) {
        return;
    }

    // 计算帧时间差（deltaTime）
    float currentTime = m_timer.elapsed() / 1000.0f;
    float deltaTime = currentTime - m_lastFrameTime;
    m_lastFrameTime = currentTime;

    // 限制deltaTime避免异常值
    if (deltaTime > 0.1f) {
        deltaTime = 1.0f / 60.0f;
    }

    // 更新旋转角度
    m_rotation += deltaTime * 45.0f;  // 每秒旋转45度
    if (m_rotation >= 360.0f) {
        m_rotation -= 360.0f;
    }

    // 清空颜色缓冲和深度缓冲
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // 渲染三角形
    renderTriangle();

    // 渲染文字（使用QPainter）
    renderText();

    // 统计FPS
    m_frameCount++;
    m_fpsUpdateTimer += deltaTime;
    if (m_fpsUpdateTimer >= 1.0f) {
        m_currentFPS = m_frameCount / m_fpsUpdateTimer;
        emit fpsChanged(m_currentFPS);
        m_frameCount = 0;
        m_fpsUpdateTimer = 0.0f;
    }

    // 请求下一帧
    update();
}

void CocosWidget::renderTriangle() {
    if (!m_shaderProgram || !m_vao) {
        return;
    }

    // 使用着色器程序
    m_shaderProgram->bind();

    // 创建变换矩阵（旋转）
    QMatrix4x4 transform;
    transform.rotate(m_rotation, 0.0f, 0.0f, 1.0f);  // 绕Z轴旋转

    // 设置uniform变量
    m_shaderProgram->setUniformValue("transform", transform);

    // 绑定VAO并绘制
    m_vao->bind();
    glDrawArrays(GL_TRIANGLES, 0, 3);
    m_vao->release();

    m_shaderProgram->release();
}

void CocosWidget::renderText() {
    // 使用QPainter在OpenGL上下文中绘制文字
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setRenderHint(QPainter::TextAntialiasing);

    // 设置字体
    QFont font("Arial", 48, QFont::Bold);
    painter.setFont(font);

    // 设置文字颜色
    painter.setPen(QColor(255, 255, 255));

    // 绘制 "Hello World"
    QString text = "Hello World";
    QRect textRect = rect();
    painter.drawText(textRect, Qt::AlignCenter, text);

    // 绘制FPS信息
    QFont smallFont("Arial", 14);
    painter.setFont(smallFont);
    painter.setPen(QColor(0, 255, 0));

    QString fpsText = QString("FPS: %1 | Rotation: %2°")
                        .arg(m_currentFPS, 0, 'f', 1)
                        .arg(m_rotation, 0, 'f', 1);
    painter.drawText(10, 30, fpsText);

    painter.end();
}

float CocosWidget::getFrameRate() const {
    return m_currentFPS;
}

void CocosWidget::cleanup() {
    makeCurrent();

    if (m_vao) {
        m_vao->destroy();
        delete m_vao;
        m_vao = nullptr;
    }

    if (m_vertexBuffer) {
        m_vertexBuffer->destroy();
        delete m_vertexBuffer;
        m_vertexBuffer = nullptr;
    }

    if (m_shaderProgram) {
        delete m_shaderProgram;
        m_shaderProgram = nullptr;
    }

    doneCurrent();
}

// =============================================================================
// Qt事件处理
// =============================================================================

void CocosWidget::mousePressEvent(QMouseEvent* event) {
    qDebug() << "[CocosWidget] Mouse pressed at:" << event->pos();
    emit cardClicked(event->pos().x(), event->pos().y());
    QOpenGLWidget::mousePressEvent(event);
}

void CocosWidget::mouseReleaseEvent(QMouseEvent* event) {
    QOpenGLWidget::mouseReleaseEvent(event);
}

void CocosWidget::mouseMoveEvent(QMouseEvent* event) {
    QOpenGLWidget::mouseMoveEvent(event);
}
